import pymongo
from urllib.parse import quote_plus
from django.conf import settings

class MongoClientManager:
    """
    MongoDB连接管理器，提供全局唯一的MongoClient实例。
    用于高效复用连接，避免频繁创建销毁。
    """
    _client = None

    @classmethod
    def get_client(cls):
        """
        获取全局MongoClient实例。
        Returns:
            pymongo.MongoClient: 已连接的MongoDB客户端
        """
        if cls._client is None:
            username = quote_plus(settings.MONGO_USERNAME)
            password = quote_plus(settings.MONGO_PASSWORD)
            host = settings.MONGO_HOST
            port = settings.MONGO_PORT
            database = settings.MONGO_AUTH_DB
            uri = f"mongodb://{username}:{password}@{host}:{port}/{database}?authSource=admin"
            cls._client = pymongo.MongoClient(uri)
        return cls._client

# 用法示例：
# from utils.mongo_client import MongoClientManager
# client = MongoClientManager.get_client()
# db = client['your_db_name'] 